package com.zh.harmony.arch.core.internal;

import java.util.HashMap;
import java.util.Map;

/**
 * 一个支持在迭代时，修改元素的Map
 */
public class FastSafeIterableMap<K, V> extends SafeIterableMap<K, V> {
    private final HashMap<K, Entry<K, V>> mHashMap = new HashMap<>();

    @Override
    protected Entry<K, V> get(K k) {
        return mHashMap.get(k);
    }

    @Override
    public V putIfAbsent(K key, V v) {
        //如果已经存在这个值了，直接返回
        Entry<K, V> current = get(key);
        if (current != null) {
            return current.mValue;
        }
        //不存在，则添加
        mHashMap.put(key, put(key, v));
        return null;
    }

    @Override
    public V remove(K key) {
        //移除
        V removed = super.remove(key);
        mHashMap.remove(key);
        return removed;
    }

    /**
     * Returns {@code true} if this map contains a mapping for the specified
     * key.
     */
    public boolean contains(K key) {
        return mHashMap.containsKey(key);
    }

    /**
     * Return an entry added to prior to an entry associated with the given key.
     *
     * @param k the key
     */
    public Map.Entry<K, V> ceil(K k) {
        if (contains(k)) {
            return mHashMap.get(k).mPrevious;
        }
        return null;
    }
}